package org.meb.intercept;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;

import javax.inject.Inject;
import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;
import javax.persistence.EntityManager;

import org.meb.speedway.bean.LogService;
import org.meb.speedway.config.SpeedwayDatabase;
import org.meb.speedway.model.common.LogKind;
import org.meb.speedway.model.common.ProcessKind;
import org.meb.speedway.model.common.ProcessLog;

@Interceptor
@Loggable
public class LoggingInterceptor {

	@Inject
	@SpeedwayDatabase
	private EntityManager em;

	@Inject
	private LogService logService;

	public LoggingInterceptor() {
	}

	@AroundInvoke
	public Object manage(InvocationContext ctx) throws Exception {
		String log = null;
		LogKind logKind = LogKind.INFO;
		try {
			log = (String) ctx.proceed();
		} catch (Exception e) {
			StringWriter sw = new StringWriter();
			e.printStackTrace(new PrintWriter(sw));
			log = sw.toString();
			logKind = LogKind.ERROR;
			throw e;
		} finally {
			ProcessLog processLog = new ProcessLog();
			processLog.setInsertDate(new Date());
			processLog.setLogKind(logKind);
			processLog.setProcessKind(ProcessKind.EVENT_TASK_IMPORT);
			processLog.setLog(log);
			logService.persistProcessLog(processLog);
		}
		return log;
	}
}
